package com.hmall.search.listener;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.hmall.search.domain.po.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author 86157
 * @Date 2025/9/11 下午6:18
 */
@Component
@Slf4j
public class ItemSyncListener {


    @Autowired
    private ElasticsearchClient esClient;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("item.save.sync.queue"),
            exchange = @Exchange(value = "item.sync.exchange", type = ExchangeTypes.DIRECT),
            key = "item.save.sync"
    ))
    public void listenItemSaveSync(ItemDoc itemDoc) throws IOException {
            esClient.index(builder -> builder
                    .index("items").id(itemDoc.getId()).document(itemDoc));
            log.info("保存商品文档,itemDoc={}", itemDoc);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("item.remove.sync.queue"),
            exchange = @Exchange(value ="item.sync.exchange", type = ExchangeTypes.DIRECT),
            key = "item.remove.sync"
    ))
    public void listenItemRemoveSync(Long id) throws IOException {

        esClient.delete(builder -> builder.index("items").id(id.toString()));
        log.info("删除商品文档,id={}", id);

    }

}
